package com.atguigu.netty.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class MyServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(8);

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))//日志
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            /**
                             * 说明
                             * IdleStateHandler 是 netty 提供的处理空闲状态的处理器
                             * 1. long readerIdleTime ：表示多长时间没有读，就会发送一个心跳检测包检测是否连接
                             * 2. long writerIdleTime ：表示多长时间没有写，就会发送一个心跳检测包检测是否连接
                             * 3. long allIdleTime ：表示多长时间没有读和写，就会发送一个心跳检测包检测是否连接
                             * 4.Triggers an IdleStateEvent when a Channel has not performed read, write, or both operation for a while.
                             * 5.当 IdleStateEvent 触发后，就会传递给管道的下一个 Handler 去处理，通过调用（触发）下一个 handler 的 userEventTriggered ,
                             *   在该方法中去处理 IdleStateEvent （读空闲，写空闲，读写空闲）
                             */
                            pipeline.addLast(new IdleStateHandler(5900,7000,10, TimeUnit.SECONDS));
                            pipeline.addLast(new MyServerHandle());//处理空闲
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
